package com.block.db.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 雪花数工具类
 * 
 * @date 2020/12/4 10:33 上午
 */
public class SnowflakeUtil {

    /**
     * 通用 19位雪花数
     * workerId暂按默认填写.后续改为数据库读取,不同应用不同.
     * 雪花数生成方法,
     * @return
     */
    public static synchronized long getSnowflakeId() {
        Snowflake snowflake = IdUtil.getSnowflake(IdTypeEnum.COMMON.getWorkId(),IdTypeEnum.COMMON.getDatacenterId());
        return snowflake.nextId();
    }

    /**
     * 指定类型的雪花数 19位
     * workerId暂按默认填写.后续改为数据库读取,不同应用不同.
     * 雪花数生成方法,
     * @return
     */
    public static synchronized long getSnowflake(IdTypeEnum idTypeEnum) {
        Snowflake snowflake    = IdUtil.getSnowflake(idTypeEnum.getWorkId(), idTypeEnum.getDatacenterId());
        return snowflake.nextId();
    }

    /**
     * 生成4位日期+19位雪花数
     * @param idTypeEnum
     * @return
     */
    public static synchronized String getSnowflakeByDate(IdTypeEnum idTypeEnum) {
        Snowflake snowflake    = IdUtil.getSnowflake(idTypeEnum.getWorkId(), idTypeEnum.getDatacenterId());
        long snow= snowflake.nextId();
        String result=getNowDateStr("yyyyMMdd").concat(snow+"");
        return result;
    }
    /**
     *
     * 生成指定长度的
     * 总长度不大于 33 不小于19位
     * @param idTypeEnum
     * @return
     */
    public static synchronized String getSnowflakeByDate(IdTypeEnum idTypeEnum,int length) {
        if(length>33){
            return  null;
        }
        if(length<19){
            return null;
        }
        int cut=length-19;
        String date=getNowDateStr("yyyyMMddHHmmssSSS");
        date=date.substring(0,cut);
        Snowflake snowflake    = IdUtil.getSnowflake(idTypeEnum.getWorkId(), idTypeEnum.getDatacenterId());
        long snow= snowflake.nextId();
        String result=date.concat(snow+"");
        return result;
    }

    public static void main(String[] args) {
       System.out.println( SnowflakeUtil.getSnowflakeByDate(IdTypeEnum.COMMON,25));
        System.out.println( SnowflakeUtil.getSnowflake(IdTypeEnum.COMMON));
        System.out.println( SnowflakeUtil.getSnowflakeByDate(IdTypeEnum.COMMON));
    }
    /**
     * 生成10位时间戳+19位雪花数
     * @param idTypeEnum
     * @return
     */
    public static synchronized String getSnowflakeByTime(IdTypeEnum idTypeEnum) {
        Snowflake snowflake    = IdUtil.getSnowflake(idTypeEnum.getWorkId(), idTypeEnum.getDatacenterId());
        long timestamp=System.currentTimeMillis()/1000;
        long snow= snowflake.nextId();
        String result=timestamp+"".concat(snow+"");
        return result;
    }

    public static String getNowDateStr(String format) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        return localTime;
    }
}

